package com.example.cloud_disk.FileReading;


import com.example.cloud_disk.constant.FileTypeConstant;
import org.apache.tika.Tika;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件类型检测工具
 *
 * @author majun
 * @package com.example.cloud_disk.FileReading
 * @date 2024/10/23 20:41
 */

@Service
public class FileTypeChecker {

    private final Tika tika = new Tika();

    public String determineFileType(MultipartFile file) throws IOException {
        // 使用 Tika 来检测文件类型
        String mimeType = tika.detect(file.getInputStream());

        if (mimeType != null) {
            switch (mimeType) {
                case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                case "application/x-tika-ooxml":
                    return FileTypeConstant.Excel;
                case "text/plain":
                    return FileTypeConstant.CSV;
                default:
                    return FileTypeConstant.Others;
            }
        } else {
            return "无法确定文件类型";
        }
    }
}

